# Appendix L
# Santiago Lopez-Cariboni, 2022. "Political Regimes and Informal Social Insurance", Comparative Political Studies.

# ---- wd ----
wd <- 'replication_materials' 
setwd(wd)

# ---- packages ----
pkgs <- c("data.table", "foreign", 'panelView', 'fect', "lubridate", 
    "ggplot2", "dplyr", "mFilter", "texreg", "AER", "xts", "interflex", "gridExtra")
suppressPackageStartupMessages(sapply(pkgs,require,character.only=T))
# Plot the effects (use Johannes Karreth's function: https://github.com/jkarreth/JKmisc/blob/master/ggintfun.R)
# devtools::source_url("https://raw.githubusercontent.com/jkarreth/JKmisc/master/ggintfun.R")
source('code/functions/ggintfun.R')
# Function for time Lags
source('code/functions/lagpanel.R')


# ---- data ----
dt <- fread('data/dt_replication.csv')
dt <- dt[LDC==1, ]


# ---- Figure L1 ----
dt <- dt[order(dt$iso3c, dt$year),] # sort for lagpanel
dt$lfail4 <- lagpanel(dt$fail, dt$iso3c, dt$year, 4) 
dt$lndura <- log(1+ dt$gwf_duration)
pdf("figures/OA/L1_fail_dura.pdf", width = 8, height = 6)
qplot(data = dt, lndura, lfail4) +
geom_smooth(method = "loess", size = 1.5)+
coord_cartesian(ylim = c(0, .4)) +
ylab("Pr(fail)") +
xlab("Regime Duration (log)")
dev.off()



# ---- Table 11 ----
dt$year1 <- (dt$year-1970)
dt$year2 <- (dt$year-1970)^2
dt$year3 <- (dt$year-1970)^3

all <- glm(archfail ~ lndura + archdura1 + polity2 + e_civil_war + log(l.pop) + log(l.gdp.pcap) + as.factor(region23) + year1 + year2 + year3
, data = dt, family = "binomial"(link = "logit"))
dem <- glm(archfail ~ lndura + archdura1 + polity2 + e_civil_war + log(l.pop) + log(l.gdp.pcap) + as.factor(region23) + year1 + year2 + year3
, data = dt[democracy==1,], family = "binomial"(link = "logit"))
auto <- glm(archfail ~ lndura + archdura1 + polity2 + e_civil_war + log(l.pop) + log(l.gdp.pcap) + as.factor(region23) + year1 + year2 + year3
, data = dt[democracy==0,], family = "binomial"(link = "logit"))
summary(all)
summary(dem)
summary(auto)


texreg(list(all, dem, auto),
    file= "tables/OA/T11_achfail.tex",
    label="tab:archfail",
    custom.model.names = c('(1)','(2)', '(3)'),
    caption="Predicted probability of leadership failure: all countries, democracies, and non-democracies",
    dcolumn = TRUE,
    no.margin=FALSE,
    fontsize="scriptsize",
    single.row=FALSE,
    use.packages=FALSE,
    booktabs = TRUE,
    digits=2,
    float.pos="htbp",
    sideways=FALSE,
    # omit.coef= "(Intercept)",
    include.rsquared = FALSE,
    stars = c(0.01, 0.05, 0.1)
    )